package active;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author 陈华旺
 * @version 1.0
 * @date 2023年11月21日 15:10
 * @Description TODO
 */
@WebServlet("/test08")
public class Test08Servlet extends HttpServlet {
//    在Servlet中不去重写 service 方法，而是基于HTTP请求类型的方式分别重写 doXXX方法
//    通过对应的方法实现分解处理,分解后的 servlet被访问时，如果没有与http请求类型对应的方法，会出现405提示
//    405 => http 请求类型对应的方法不存在
//    如果doXXXX方法和service 方法同时重写，所有请求优先执行service

//    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String addr = req.getParameter("addr");
        System.out.println("name:"+name);
        System.out.println("addr:"+addr);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println("/test08 - Test08Servlet - doGet - 测试页test08Method.html");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = new String( req.getParameter("name").getBytes(StandardCharsets.ISO_8859_1) );
        String addr = new String( req.getParameter("addr").getBytes(StandardCharsets.ISO_8859_1) );
        System.out.println("name:"+name);
        System.out.println("addr:"+addr);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println("/test08 - Test08Servlet - doPost - 测试页test08Method.html");
    }

    protected void doOther(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println("/test08 - Test08Servlet - doOther - 测试页test08Method.html");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        当前Servlet地址对应的统一请求方法，所有当前地址的HTTP请求都由该方法处理(get,post……)
//        System.out.println( req.getMethod() );
        String method = req.getMethod();
        switch (method){
            case "GET": doGet(req,resp); break;
            case "POST": doPost(req,resp); break;
            default: doOther(req,resp); break;
        }
//        resp.setContentType("text/html;charset=utf-8");
//        PrintWriter writer = resp.getWriter();
//        writer.println("/test08 - Test08Servlet - service - 测试页test08Method.html");
    }
}
